package com.example.tbs.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tbs.common.ServerResponse;
import com.example.tbs.demo.entity.TbsFy;
import com.example.tbs.demo.entity.TbsHd;
import com.example.tbs.demo.entity.TbsYh;
import com.example.tbs.demo.mapper.TbsFlMapper;
import com.example.tbs.demo.mapper.TbsFyMapper;
import com.example.tbs.demo.mapper.TbsHdMapper;
import com.example.tbs.demo.mapper.TbsYhMapper;
import com.example.tbs.demo.service.ITbsService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class TbsServiceImpl extends ServiceImpl<TbsFyMapper, TbsFy> implements ITbsService{

    @Resource
    private TbsHdMapper tbsHdMapper;

    @Resource
    private TbsFlMapper tbsFlMapper;
    @Resource
    private TbsYhMapper tbsYhMapper;

    @Resource
    private TbsFyMapper tbsFyMapper;


    @Override
    public BigDecimal getRateByAreaCode(String areaCode) {
        return tbsFlMapper.getRateByAreaCode(areaCode);
    }
    @Override
    public void calculateBilling() {
        // 获取所有通话记录
        List<TbsHd> callRecords = tbsHdMapper.selectList(null);

        for (TbsHd record : callRecords) {
            String callerAreaCode = record.getCallerAreaCode();
            String calledAreaCode = record.getCalledAreaCode();
            int duration = record.getCallDuration();

            BigDecimal callFee ;

            // 判断通话类型
            if (callerAreaCode.equals(calledAreaCode)) {
                // 本地通话
                callFee = calculateLocalCallFee(duration);
            } else {
                // 长途通话
                BigDecimal rate =getRateByAreaCode(calledAreaCode);
                callFee = calculateLongDistanceCallFee(duration, rate);
            }

            // 保存到费用文件表
            TbsFy tbsFy = new TbsFy();
            String rawUuid = UUID.randomUUID().toString(); // 示例: "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"

// 移除短横线后为 32 字符
            String uuid32 = rawUuid.replace("-", ""); // 示例: "a0eebc999c0b4ef8bb6d6bb9bd380a11"

// 设置为 32 字符的纯 UUID（不带前缀）
            tbsFy.setUniqueCode(uuid32);
            tbsFy.setCallerNumber(record.getCallerNumber());
            tbsFy.setCallType(callerAreaCode.equals(calledAreaCode) ? "本地" : "长途");
            tbsFy.setCallFee(callFee);

            tbsFyMapper.insert(tbsFy);
        }
    }

    @Override
    public ServerResponse getBillingInfo(String phoneNumber) {
        // 查询用户信息
        TbsYh user = tbsYhMapper.selectOne(new QueryWrapper<TbsYh>().eq("user_number", phoneNumber));
        if (phoneNumber == null){
            return ServerResponse.createByNokeyError();
        }
        if ( phoneNumber.trim().isEmpty()) {
            return ServerResponse.createByNoDataError();
        }

        if (user == null) {
            return  ServerResponse.createByNoUserError();
        }

        // 查询费用信息
        List<TbsFy> billingRecords = tbsFyMapper.selectList(new QueryWrapper<TbsFy>().eq("caller_number", phoneNumber));
        BigDecimal localFee = BigDecimal.ZERO;
        BigDecimal longDistanceFee = BigDecimal.ZERO;

        for (TbsFy record : billingRecords) {
            if ("本地".equals(record.getCallType())) {
                localFee = localFee.add(record.getCallFee());
            } else {
                longDistanceFee = longDistanceFee.add(record.getCallFee());
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("userName", user.getUserName()); // 用户姓名
        result.put("phoneNumber", phoneNumber); // 用户手机号
        result.put("localFee", localFee); // 本地通话费用
        result.put("longDistanceFee", longDistanceFee); // 长途通话费用
        result.put("totalFee", localFee.add(longDistanceFee)); // 总费用

        return ServerResponse.createBySuccess(result);
    }
    @Override
    public ServerResponse getCallRecords(String phoneNumber) {
        String userName = tbsYhMapper.getUserNameByPhoneNumber(phoneNumber);

        if (phoneNumber == null){
            return ServerResponse.createByNokeyError();
        }
        if ( phoneNumber.trim().isEmpty()) {
            return ServerResponse.createByNoDataError();
        }
        if (userName == null) {
            return  ServerResponse.createByNoUserError();
        }


        // 查询通话记录
        List<Map<String, Object>> callRecords = tbsHdMapper.getCallRecordsByPhoneNumber(phoneNumber);

        // 组合结果
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> record : callRecords) {
            Map<String, Object> formattedRecord = new HashMap<>();
            formattedRecord.put("用户名", userName);
            formattedRecord.put("主叫电话号码", record.get("caller_number"));
            formattedRecord.put("被叫电话号码", record.get("called_number"));
            formattedRecord.put("通话时长", record.get("call_duration"));
            result.add(formattedRecord);
        }

        return ServerResponse.createBySuccess(result);
    }


    // 判断通话类型的方法
    private String determineCallType(TbsHd record) {
        String callerAreaCode = record.getCallerAreaCode();
        String calledAreaCode = record.getCalledAreaCode();
        return callerAreaCode.equals(calledAreaCode) ? "本地" : "长途";
    }
    private BigDecimal calculateLocalCallFee(int duration) {
        if (duration <= 180) {
            return new BigDecimal("0.50");
        } else {
            int extraMinutes = (int) Math.ceil((duration - 180) / 180.0);
            return new BigDecimal("0.50").add(new BigDecimal("0.20").multiply(new BigDecimal(extraMinutes)));
        }
    }

    private BigDecimal calculateLongDistanceCallFee(int duration, BigDecimal rate) {
        int minutes = (int) Math.ceil(duration / 60.0);
        return rate.multiply(new BigDecimal(minutes)).setScale(2, RoundingMode.HALF_UP);
    }
}


